package 链表;

import java.util.Stack;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/5/6 19:38
 * @Description:
 */
public class 反转链表 {

    public ListNode reverseList(ListNode head) {
        if(head == null){
            return head;
        }
        // 压栈 1111
        Stack<ListNode> stack = new Stack<>();
        ListNode cur = head;
        while(cur != null){
            stack.push(cur);
            cur = cur.next;
        }
        ListNode result = stack.pop();
        cur = result;
        while (!stack.isEmpty()){
            ListNode peek = stack.pop();
            cur.next = peek;
            cur = peek;
        }
        cur.next = null; // head节点的next必须为null
        return result;
    }


    public static void main(String[] args) {


    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


}




